﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Configuration;
using System.Text;

namespace Savage.DotNetLibrary.WebLibrary
{
    public static class WebConfiguration
    {
        public static void ConfigureApplication(string defaultConfigDirectory, string configDirectory, string applicationVirtualPath, bool generateMachineKey)
        {
            CopyDefaultConfiguration(defaultConfigDirectory, configDirectory);
            
            if (generateMachineKey)
                AddMachineKey(applicationVirtualPath);
        }

        private static void CopyDefaultConfiguration(string defaultConfigDirectory, string configDirectory)
        {
            //Copy the default config files into place.
            
            //Iterate over each file in the default
            foreach (string filePath in System.IO.Directory.GetFiles(defaultConfigDirectory, "*.config"))
            {
                string fileName = System.IO.Path.GetFileName(filePath);
                string localFilePath = configDirectory + @"\" + fileName;

                //See if this config file is loaded in the config directory
                if (!System.IO.File.Exists(localFilePath))
                {
                    //File doesn't exist, Copy the default config file into the config directory
                    System.IO.File.Copy(filePath, localFilePath, false);
                }
            }
        }

        public static void AddMachineKey(string applicationVirtualPath)
        {
            //Has a machine key been set?
            Configuration config = WebConfigurationManager.OpenWebConfiguration(applicationVirtualPath);
            MachineKeySection machineKey = config.GetSection("system.web/machineKey") as System.Web.Configuration.MachineKeySection;
            if (machineKey.Decryption == "Auto")
            {
                MachineKeyGenerator mkg = new MachineKeyGenerator();
                machineKey.Validation = System.Web.Configuration.MachineKeyValidation.SHA1;
                machineKey.ValidationKey = mkg.ValidationKey;

                machineKey.Decryption = "AES";
                machineKey.DecryptionKey = mkg.DecryptionKey;

                config.Save(ConfigurationSaveMode.Minimal);
            }
        }
    }
}
